<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <select id="userId">
        <option value=1>1</option>
        <option value=2>2</option>
        <option value=3>3</option>
        <option value=4>4</option>
        <option value=5>5</option>
        <option value=6>6</option>
    </select>
    <button onclick="closeSource()">Close</button>
    <button onclick="registerSource()">Open</button>
    <div id="result"></div>
</body>

<script>
    const url = '/async/sse/events/'

    function closeSource() {
        window.source.close()
        console.log('close current source');
    }

    function registerSource() {
        let id = document.getElementById('userId').value
        window.source = new EventSource(url+id);

        source.onopen = function (event) {
            console.log(event);
        };

        source.onmessage = function (event) {
            var data = event.data;
            // handle message
            console.log(data);
            document.getElementById('result').append(data)
        };

        source.onerror = function (event) {
            // handle error event
            console.log('error or complete');
            var div = document.createElement("br");
            document.getElementById('result').appendChild(div)
        };
    }
</script>

</html>